<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Goods;
use App\User;
use DB;

class CartController extends Controller
{
    //
    public function insert(Request $request)
    {
    	//将该商品加入到购物车表中
		$user = User::findOrFail(session('id'));
		$goods= Goods::findOrFail($request->id);

		//检测用户之前是否添加过该商品
		if($this->checkExists($request->id)) {
			//调整数量
			$this->increNum($request->id, $request->num);
			return view('home.remind.addcart');
		}
		//手动插入数据库
		// DB::table('carts')->insert(['goods_id'=>$request->id,'user_id'=>session('id'),'number'=>$request->num]);

		if($user->cart_goods()->save($goods,[
				'number'=>$request->num
				])) {
			return view('home.remind.addcart');

		}
    }


    private function checkExists($id)
    {//$a && echo 'abc'       ||     make && make instart
    	return DB::table('carts')->where('goods_id',$id)->where('user_id',session('id'))->first() ? true : false;
    }

    private function increNum($id, $num)
    {
    	//读取原来的数量
    	$res = DB::table('carts')->where('goods_id',$id)->where('user_id',session('id'))->first();

    	//修改数量
    	$number = $res->number + $num;

    	//更新数据库
    	return DB::table('carts')->where('goods_id',$id)->where('user_id', session('id'))->update(['number'=>$number])

    }

    /**
     * 购物车页面
     */
    public function index()
    {
    	//读取当前登陆用户的购物车信息
    	$user = User::find(session('id'));

        // var_dump($id);
        

    	$goods = $user->cart_goods;

    	return view('home.cart.index',['goods'=>$goods]);
    }
}
